package com.zscat.mallplus.single;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.dms.service.IMealService;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.mapper.UmsMemberMapper;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.UserUtils;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: shenzhuan
 * @Date: 2019/4/2 15:02
 * @Description:
 */
@RestController
@Api(tags = "OmsController", description = "订单管理系统")
@RequestMapping("/api/single/oms")
public class SingeOmsController extends ApiBaseAction {
    @Resource
    private UmsMemberMapper memberMapper;
    @Autowired
    private IDmsOrderService dmsOrderService;
    @Autowired
    private IMealService mealService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IQsgTeachingAssistantorderService teachingAssistantorderService;
    @Autowired
    private IQsgTeachingAssistantService teachingAssistantService;

    @IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "查询教练订单列表")
    @ApiOperation(value = "查询教练订单列表")
    @GetMapping(value = "/coachOrderList/list")
    public Object coachOrderList(@RequestParam String status,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                                  @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {

        UmsMember member = UserUtils.getCurrentMember();
        if (member == null) {
            return new CommonResult().failed("请先登录");
        }
        IPage<DmsOrder> page = null;
        if ("0".equalsIgnoreCase(status)) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("member_id",member.getId());
            List<Integer> statues = new ArrayList<>();
            statues.add(OrderStatus.COMPLETED.getValue());
            statues.add(OrderStatus.HAS_PAYMONEY.getValue());
            statues.add(OrderStatus.WAIT_CANNEL.getValue());
            statues.add(OrderStatus.REFUND.getValue());
            statues.add(OrderStatus.PAYMENT.getValue());
            qw.in("order_status",statues);
            qw.orderByDesc("create_datetime");
            page = dmsOrderService.page(new Page<DmsOrder>(pageNum, pageSize), qw);
        } else {
            QueryWrapper qw = new QueryWrapper();
            String[] statusArr = StringUtils.split(status, ",");
            List<Integer> currentStatusArr = new ArrayList<>();
            for (String s : statusArr
            ) {
                currentStatusArr.add(Integer.parseInt(s));
            }
            qw.in("order_status", currentStatusArr);
            qw.eq("member_id", member.getId());
            qw.orderByDesc("create_datetime");
            page = dmsOrderService.page(new Page<>(pageNum, pageSize), qw);
        }
        for (DmsOrder order : page.getRecords()) {
            if (order.getOrderStatus()==OrderStatus.HAS_PAYMONEY.getValue()){
                Date endTime = DateUtil.StringToDate(order.getEndTime(),"yyyy/MM/dd HH:mm");
                Date startTime = DateUtil.StringToDate(order.getStartTime(),"yyyy/MM/dd HH:mm");
                if (new Date().compareTo(startTime)<0||new Date().compareTo(endTime)>0){
                    order.setShowStatus(1);
                }
            }
            QsgDevice device = deviceService.getById(order.getDeviceId());
            order.setDevice(device);
        }
        return new CommonResult().success(page);
    }

    @IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "查询教练订单列表")
    @ApiOperation(value = "查询教练订单列表")
    @PostMapping(value = "/coachOrderList/listAdmin")
    public Object listAdmin(@RequestBody(required = false) DmsOrder par) {
        IPage<DmsOrder> page = null;
        if ("0".equalsIgnoreCase(par.getStatus())) {
//            DmsOrder params = new DmsOrder();
//            params.setStoreId(par.getStoreId());
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",par.getStoreId());
//            List<Integer> statues = new ArrayList<>();
//            statues.add(OrderStatus.INIT.getValue());
//            qw.notIn("order_status",statues);
            qw.orderByDesc("create_datetime");
            page = dmsOrderService.page(new Page<DmsOrder>(par.getPageNum(), 10), qw);
        } else {
            QueryWrapper qw = new QueryWrapper();
            String[] statusArr = StringUtils.split(par.getStatus(), ",");
            List<Integer> currentStatusArr = new ArrayList<>();
            for (String s : statusArr
            ) {
                currentStatusArr.add(Integer.parseInt(s));
            }
            qw.in("order_status", currentStatusArr);
            qw.eq("store_id", par.getStoreId());
            qw.orderByDesc("create_datetime");
            page = dmsOrderService.page(new Page<>(par.getPageNum(), 10), qw);
        }
        for (DmsOrder order : page.getRecords()) {
            UmsMember member = memberMapper.selectById(order.getMemberId());
            if (null!=member){
                order.setPhone(member.getPhone());
            }
//            if (order.getOrderStatus()==OrderStatus.HAS_PAYMONEY.getValue()){
//                Date endTime = DateUtil.StringToDate(order.getEndTime(),"yyyy/MM/dd HH:mm");
//                Date startTime = DateUtil.StringToDate(order.getStartTime(),"yyyy/MM/dd HH:mm");
////                if (new Date().compareTo(endTime)>0){
////                    order.setOrderStatus(OrderStatus.COMPLETED.getValue());
////                    dmsOrderService.updateById(order);
////                }
//                if (new Date().compareTo(startTime)<0){
//                    order.setShowStatus(1);
//                }
//            }
            QsgDevice device = deviceService.getById(order.getDeviceId());
            if (null==device){
                device = new QsgDevice();
                device.setImageUrl("");
            }
            order.setDevice(device);
        }
        return new CommonResult().success(page);
    }

    @ApiOperation(value = "根据用户查询订单")
    @ResponseBody
    @RequestMapping(value = "/coachOrderList/listByMember")
    public Object listByMember(Long memberId,Long storeId) {
        IPage<DmsOrder> page = null;
        QueryWrapper qw = new QueryWrapper();
        List<Integer> stauses = new ArrayList<>();
        stauses.add(OrderStatus.HAS_PAYMONEY.getValue());
        stauses.add(OrderStatus.COMPLETED.getValue());
        qw.in("order_status", stauses);
        qw.eq("store_id", storeId);
        qw.eq("member_id",memberId);
        qw.isNull("integral");
        qw.orderByDesc("create_datetime");
//        page = dmsOrderService.page(new Page<>(par.getPageNum(), 10), qw);
        List<DmsOrder> orders = dmsOrderService.list(qw);
        return new CommonResult().success(orders);
    }

    @IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "查询教练订单列表")
    @ApiOperation(value = "查询教练订单列表")
    @GetMapping(value = "/coachOrderList/storelist")
    public Object storelist(@RequestParam String status,@RequestParam Long storeId,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                                 @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {

        IPage<DmsOrder> page = null;
        if ("0".equalsIgnoreCase(status)) {
            DmsOrder params = new DmsOrder();
            params.setStoreId(storeId);
            page = dmsOrderService.page(new Page<DmsOrder>(pageNum, pageSize), new QueryWrapper<DmsOrder>(params).orderByDesc("create_datetime"));
        } else {
            QueryWrapper qw = new QueryWrapper();
            String[] statusArr = StringUtils.split(status, ",");
            List<Integer> currentStatusArr = new ArrayList<>();
            for (String s : statusArr
            ) {
                currentStatusArr.add(Integer.parseInt(s));
            }
            qw.in("order_status", currentStatusArr);
            qw.eq("store_id", storeId);
            qw.orderByDesc("create_datetime");
            page = dmsOrderService.page(new Page<>(pageNum, pageSize), qw);
        }
        for (DmsOrder order : page.getRecords()) {
            List<QsgMeal> meals = mealService.list(new QueryWrapper<QsgMeal>().eq("id", order.getMealId()));
            order.setMeals(meals);
            QsgDevice device = deviceService.getById(order.getDeviceId());
            order.setDevice(device);
        }
        return new CommonResult().success(page);
    }

    @SysLog(MODULE = "dms", REMARK = "关闭订单")
    @ApiOperation("关闭订单")
    @RequestMapping(value = "/driverorder/closeDriverOrder", method = RequestMethod.POST)
    public Object closeDriverOrder(@ApiParam("订单id") @RequestParam Long orderId) {
        try {
            if (ValidatorUtils.empty(orderId)) {
                return new CommonResult().paramFailed("订单id is empty");
            }
            DmsOrder order = dmsOrderService.getById(orderId);
            if (order.getOrderStatus() != OrderStatus.INIT.getValue() && order.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
                return new CommonResult().paramFailed("订单当前状态不支持删除!");
            }
            order.setOrderStatus(OrderStatus.CLOSED.getValue());
            if (dmsOrderService.closeOrder(order)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }


    @IgnoreAuth
    @SysLog(MODULE = "qsg", REMARK = "查询助教订单列表")
    @ApiOperation(value = "查询助教订单列表")
    @GetMapping(value = "/assistantOrderList/list")
    public Object assistantOrderList(@RequestParam String status,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                                 @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {

        UmsMember member = UserUtils.getCurrentMember();
        if (member == null) {
            return new CommonResult().failed("请先登录");
        }
        IPage<QsgTeachingAssistantorder> page = null;
        if ("0".equalsIgnoreCase(status)) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("member_id",member.getId());
            List<Integer> statues = new ArrayList<>();
            statues.add(OrderStatus.COMPLETED.getValue());
            statues.add(OrderStatus.HAS_PAYMONEY.getValue());
            statues.add(OrderStatus.WAIT_CANNEL.getValue());
            statues.add(OrderStatus.PAYMENT.getValue());
            qw.in("order_status",statues);
            qw.orderByDesc("create_datetime");
            page = teachingAssistantorderService.page(new Page<QsgTeachingAssistantorder>(pageNum, pageSize), qw);
        } else {
            QueryWrapper qw = new QueryWrapper();
            String[] statusArr = StringUtils.split(status, ",");
            List<Integer> currentStatusArr = new ArrayList<>();
            for (String s : statusArr
            ) {
                currentStatusArr.add(Integer.parseInt(s));
            }
            qw.in("order_status", currentStatusArr);
            qw.eq("member_id", member.getId());
            qw.orderByDesc("create_datetime");
            page = teachingAssistantorderService.page(new Page<>(pageNum, pageSize), qw);
        }
        for (QsgTeachingAssistantorder order : page.getRecords()) {
            QsgTeachingAssistant assistant = teachingAssistantService.getById(order.getAssistantId());
            order.setTeachingAssistant(assistant);
        }
        return new CommonResult().success(page);
    }
}
